<template>
  <div class="question-header-container" id="question">
    <div class="question-header-title">
      <div class="header-title" :title="question.name">
        {{ question.name }}
      </div>
    </div>
    <el-drawer size="650px" class="eldrawer" title="题目列表" direction="ltr" v-model="listshow" :with-header="false">
      <Questionlist v-show="listshow" :change="changePage" :questions="questionlist"
        :getquestioncount="getquestioncount" :questionbankid="questionbankid" :limit="limit" :offset="offset"
        :order="order" :ID="ID" @update:listshow="hiddenList">
      </Questionlist>
    </el-drawer>
    <div class="question-header-row">
      <div v-if="showChgPageBtn" class="question-chg-page-btn-box">
        <el-button class="question-chg-page-btn" :disabled="des === 'T' || questionlist.length == 1"
          @click="goNext(true)" type="primary" plain size="default">
          <el-icon>
            <ArrowLeft />
          </el-icon>
          上一题
        </el-button>
        <span>
          &nbsp;{{ questionlist.findIndex((v) => v?.ID == ID) + 1 }} / {{ questionlist.length }} &nbsp;({{ page
          }}页)&nbsp;
        </span>
        <el-button class="question-chg-page-btn" @click="goNext(false)"
          :disabled="des === 'F' || questionlist.length == 1" type="primary" plain size="default">
          下一题
          <el-icon>
            <ArrowRight />
          </el-icon>
        </el-button>
      </div>
      <el-button class="question-question-list-btn" @click.stop="listshow = !listshow" type="primary" plain
        size="default">
        <svg class="icon" aria-hidden="true">
          <use xlink:href="#icon-Menu" />
        </svg>
        &nbsp; 查看题目列表
      </el-button>
      <el-tooltip class="item" effect="dark" :content="String(answer)" placement="top-start">
        <el-button class="question-question-list-btn" type="primary" plain size="default">
          <svg class="icon" aria-hidden="true">
            <use xlink:href="#icon-icon_tijiaodaan" />
          </svg>
          &nbsp; 查看答案
        </el-button>
      </el-tooltip>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ElDrawer } from 'element-plus';
import { computed, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import { Iobj } from '../../../api';
import { Storekey } from "../../../interface";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { delay } from '../../../util/time';
import Questionlist from "./questionlist.vue";

const router = useRouter();
const route = useRoute();
const store = useStore(Storekey);

const prop = defineProps<{ ID: number, question: Studycodemodel.Iquestion, questionlist: Studycodemodel.Iquestion[] }>()
const ID = computed(() => {
  return prop.ID;
});
const questionlist = computed(() => {
  return prop.questionlist
});

const listshow = ref(false);
function hiddenList(v: boolean) {
  listshow.value = v;
}
// routeQuery
const routeQuery = computed<{ order: string; offset: number; limit: number, questionbankid?: number, userId?: number, teamid?: string[] }>(
  () => {
    return route.query as any;
  }
);
const questionbankid = computed(() => {
  return route.query.questionbankid as string | number | undefined;
});
const userId = computed(() => {
  return route.query.userId;
});
const order = computed(() => {
  return (routeQuery.value.order || "ID") as keyof Studycodemodel.Iquestion
});
const teamid = computed(() => {
  return routeQuery.value.teamid
})

const getquestioncount = computed<number>(() => {
  // 专题是单独获取的题目列表
  if (questionbankid.value || userId.value) {
    return questionlist.value.length
  }
  // 题库、比赛、任务
  return store.getters.getquestioncount;
});

// 
const showChgPageBtn = computed(() => {
  return !!(route.query.jobid || route.query.activityid || questionbankid.value)
})


const des = computed<false | "T" | "F">(() => {
  const currQuestionIdx = questionlist.value.findIndex((v) => v?.ID == ID.value);
  // 上一题不可点击
  if (currQuestionIdx === 0 && offset.value == 0) {
    return "T";
  }
  // 下一题不可点击（仅在列表已全部加载时禁用）
  if (currQuestionIdx === questionlist.value.length - 1 && offset.value + limit.value >= getquestioncount.value) {
    return "F";
  }
  return false;
});
// 题目列表 分页用
const page = computed(() => {
  return Math.floor(offset.value / limit.value) + 1;
});

const offset = computed<number>({
  get() {
    return Number(routeQuery.value.offset) || 0;
  },
  set(v) {
    if (v !== routeQuery.value.offset) {
      router.push({
        query: { ...route.query, offset: v, showFirst: true },
      });
    }
  },
});
const limit = computed<number>({
  get() {
    let defaultLimit = 20
    if (questionbankid.value || userId.value) {
      defaultLimit = questionlist.value.length
    }
    return Number(routeQuery.value.limit) || defaultLimit;
  },
  set(v) {
    if (v !== routeQuery.value.limit) {
      router.push({
        query: { ...routeQuery.value, limit: v, },
      });
    }
  },
});

function changePage(r: number) {
  offset.value = (r - 1) * limit.value;

}
// 下一题false、上一题true
async function goNext(isPrev: boolean) {
  const currQuestionIdx = questionlist.value.findIndex((v) => v?.ID == ID.value);
  let newId: number | undefined;
  let pageChangeOffset = 0;
  let shouldLoadQuestions = false;  // 新增变量用于判断是否需要加载新题目

  if (!isPrev && currQuestionIdx === questionlist.value.length - 1) {
    // 需要翻页到下一页
    shouldLoadQuestions = true;
    pageChangeOffset = limit.value;
  } else if (isPrev && currQuestionIdx === 0) {
    // 需要翻页到上一页
    shouldLoadQuestions = true;
    pageChangeOffset = -limit.value;
  }

  if (shouldLoadQuestions) {
    await loadQuestions(offset.value + pageChangeOffset);  // 加载新的一页题目
    await delay(30);  // 等待数据加载完成

    newId = isPrev ? questionlist.value[limit.value - 1]?.ID : questionlist.value[0]?.ID; // 设置新题目ID
  } else {
    // 如果不需要翻页，则直接设置新的题目ID
    newId = isPrev ? questionlist.value[currQuestionIdx - 1]?.ID : questionlist.value[currQuestionIdx + 1]?.ID;
  }

  if (newId) {
    const query = { ...route.query, showFirst: undefined };
    if (pageChangeOffset !== 0) {
      query.offset = offset.value + pageChangeOffset;
    }
    router.push({ params: { ID: newId }, query });  // 更新路由参数
  }
}

async function loadQuestions(newOffset: number) {
  const obj: Iobj<Studycodemodel.Iquestion> = {
    _offset: newOffset,
    _limit: limit.value, _order: order.value,
  };

  if (teamid.value && Array.isArray(teamid.value)) {
    obj.teamid = store.state.team?.rows.filter(e => teamid.value.includes(String(e.ID || ''))).map(e => e.ID);
  }
  if (route.query.ID) {
    obj.ID = route.query.ID;
  }
  if (route.query.name) {
    obj._like = ["name", route.query.name];
    const id = Number(route.query.name);
    if (id == Number(route.query.name)) {
      obj._like = ["ID", id];
    }
  }
  if (route.query.range) {
    obj.range = route.query.range;
  } else {
    obj.range = 'public';
  }
  if (route.query.jobid) {
    (obj as any).jobid = route.query.jobid;
  }
  if (route.query.activityid) {
    (obj as any).activityid = route.query.activityid;
  }

  // 专题、最近练习是单独接口获取题目列表
  if (!questionbankid.value || !userId.value) {
    await store.dispatch("actionquestion", obj);
  }
}

const answer = computed(() => {
  if (prop.question.answer) {
    return String(prop.question.answer.answer) || "";
  }
  return "";
});
</script>

<style scoped>
.question-header-container {
  --container-margin: 20px;
}

.question-header-row,
.question-header-title {
  height: var(--container-header-height);
  display: flex;
  align-items: center;
}

.question-header-title {
  justify-content: center;
}

.header-title {
  font-size: 1.5rem;
  text-align: center;
  /* width: 500px; */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.header-activityTag {
  margin-left: 10px;
  /* display: inline-block; */
}

.question-drawer-container {
  height: 80vh;
}

.question-chg-page-btn-box {
  /* width: 202px; */
  display: inline-block;
  margin-right: 10px;
}

/* 翻页按钮 */
.question-chg-page-btn {
  width: 75px;
  height: 32px;
  border-radius: 4px;
  border: 1px solid rgb(134, 154, 196);

}

.question-question-list-btn {
  margin-right: calc(var(--container-margin)/2) !important;
  margin-left: 0 !important;
  border-radius: 4px;
  border: 1px solid rgba(70, 131, 250, 1);
}
</style>